package ge.modules.utils;

import ge.engine.Log;
import ge.exceptions.FunctionNonSuported;
import ge.lowlevel.DrawEngine;
import ge.lowlevel.js.JSDrawEngine;
import ge.modules.Module;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import com.google.gwt.user.client.Window;

/*
 *  That class helps you to control what images has been loaded and are ready for draw in theengine
 * @author abel.botrdonado
 *
 */
public class LoadImageModule implements Module 
{

	private Set<String> forLoad;
	private Set<String> loaded;
	/**
	 * Constrctor
	 */
	public LoadImageModule()
	{
		forLoad = new HashSet<String>();
		loaded =  new HashSet<String>();
	}
	/**
	 * 	The image asked to be loaded
	 * @param image Url of the image
	 */
	public void loadImages(String image)
	{
	
		if(forLoad.add(image))
		{
			
			try {
				DrawEngine.get().loadImage(image);
			} catch (FunctionNonSuported e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	/**
	 * 	Array of images asked to be loaded
	 * @param images Urls of images
	 */
	public void loadImages(String[] images)
	{
		 
		for(String s : images)
		{
			loadImages(s);
		}
	}
	/**
	 * 
	 * @param image url from the image
	 * @return True if the image is loaded
	 */
	public boolean isImageLoaded(String image)
	{
		return loaded.contains(image);
	}
	/**
	 * 
	 * @return True if all images has been loaded
	 */
	public boolean isAllImagesLoaded()
	{
		return forLoad.isEmpty();
	}
	/**
	 * 
	 * @return Total of images loaded %100
	 */
	public double getPerCentLoaded()
	{
		
		if(loaded.isEmpty() && forLoad.isEmpty())
			return 100;
		
		double perCent = loaded.size()/(float)(loaded.size()+forLoad.size());
		perCent *= 100;
		//Log.write(perCent);
		return perCent;
	}
	@Override
	public void update() 
	{
		if(forLoad.isEmpty())
			return;
		ArrayList<String> imagesToLoad = new ArrayList<String>();
		Iterator<String> it = forLoad.iterator();
		
		while(it.hasNext())
		{
			String elemento = it.next();
			try {
				
				if(DrawEngine.get().isImageLoaded(elemento))
				{
					//Log.write("Cargado");
					imagesToLoad.add(elemento);
					//Log.write(elemento+" cargado (LoadImageModule)");
					loaded.add(elemento);
				}
			} catch (FunctionNonSuported e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if(!imagesToLoad.isEmpty())
			forLoad.removeAll(imagesToLoad);
		 
		//Log.write(forLoad.size()+"/"+loaded.size());
	}

	@Override
	public void draw() {
		 
		
	}

	@Override
	public void delete() {
		 forLoad.clear();
		 loaded.clear();
		
	}
	
}
